#include "debug.h"
#include "avi.h"
#include "record.h"
#include "avi_sink.h"

static int create_sink_name(int chn,struct record_sink *recsink, int mode)
{
    char dirname[64] = {0};
    struct tm *nowtime;
    struct tm mytm;

    nowtime = localtime_r(&recsink->ctime,&mytm);
    snprintf(dirname,sizeof(dirname), "%s/%04d%02d%02d", recsink->mpoint, 
	    nowtime->tm_year+1900,nowtime->tm_mon+1, nowtime->tm_mday);

    if (access(dirname, 0) && mkdir(dirname, S_IRWXU | S_IRWXG | S_IRWXO)) 
    {
	SLOG(ERR, "%s doesnot exist.\n", dirname);
	return -1;
    }

    sprintf(recsink->sname, "%s/%02d%02d%02d_%d.avi", dirname, 
	    nowtime->tm_hour, nowtime->tm_min, nowtime->tm_sec, chn);

    /// avoid same record file exists
    remove(recsink->sname);

    return 0;
}

RSC_SINK_HANDLE avi_init_sink(int chn,struct record_sink *recsink, 
	struct rsc_stream_confset *media,struct rsc_mode_attr *mode)
{
    if(recsink==NULL || mode==NULL)
    {
	SLOG(ERR,"invalid params!\n");
	return NULL;
    }
    if(create_sink_name(chn,recsink,mode->mode)<0)
    {
	SLOG(ERR,"create_sink_name fail!\n");
	return NULL;
    }
    AVI_HANDLE sink_handle = NULL;
    struct avi_media_param mparam;
    int strtype = AVI_STREAM_VAMIX;

    mparam.video_codec = 1; // H264
    mparam.pic_level = 1;
    mparam.audio_sample_fmt = 8;
    mparam.audio_codec = 1;// G711

    if(media->strset==(RSC_STREAM_VIDEO|RSC_STREAM_AUDIO))
	strtype = AVI_STREAM_VAMIX;
    else if(media->strset== RSC_STREAM_VIDEO)
	strtype = AVI_STREAM_VIDEO;
    else if(media->strset== RSC_STREAM_AUDIO)
	strtype = AVI_STREAM_AUDIO;

    sink_handle = avi_init_handle(recsink->fname,&mparam,strtype);
    return sink_handle;
}

int avi_fill_sink(RSC_SINK_HANDLE sink_handle,int subtype,struct record_frame_info *frame)
{
    if(sink_handle == NULL)
    {
	SLOG(ERR,"sink_handle is null!\n");
	return -1;
    }
    if(frame == NULL)
    {
	SLOG(ERR,"frame is null!\n");
    }
    int ret = 0;
    int type = 0;

    if(subtype == REC_DTYPE_VIDEO)
	type = 0;
    else if(subtype == REC_DTYPE_AUDIO)
	type = 1;
    else if(subtype == REC_DTYPE_META)
	type = 2;

    ret = avi_write_packet((AVI_HANDLE)sink_handle,type,frame->addr,frame->len);

    return ret;
}

int avi_exit_sink(RSC_SINK_HANDLE sink_handle)
{
    avi_exit_handle((AVI_HANDLE)sink_handle); 
    return 0;
}

